package src.leetcode.everyday.hard_1289;

/**
 * @author liyizzz
 * @description 下降路径最小和 II
 * @date 2025/1/14 15:38
 */
public class minFallingPathSum {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.minFallingPathSum(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
    }
}

class Solution {
    public int minFallingPathSum(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        if (m < 2) return grid[0][0];
        int[] dp = new int[m];
        for (int j = 0; j < m; j++) {
            dp[j] = grid[0][j];
        }

        int min = 0;
        int mint = 0;
        int min_idx = -1;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[j] = grid[i][j] + (j == min_idx ? mint : min);
            }

            min = Integer.MAX_VALUE;
            mint = min;
            min_idx = 0;

            for (int j = 0; j < m; j++) {
                if (dp[j] < min) {
                    mint = min;
                    min = dp[j];
                    min_idx = j;
                } else if (dp[j] < mint) {
                    mint = dp[j];
                }
            }
        }

        int ans = Integer.MAX_VALUE;
        for (int j = 0; j < m; j++) {
            ans = Math.min(ans, dp[j]);
        }
        return ans;
    }
}